package messagesvc.websocket.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.ucloud.microsf.messagesvc.websocket.service.WsSession;
import java.nio.charset.Charset;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

@Slf4j
@Component
public class MessageInterceptor implements HandshakeInterceptor {

  /**
   * 握手前
   */
  @Override
  public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
      WebSocketHandler wsHandler, Map<String, Object> attributes) {
    log.info("开始握手....");
    // 获得请求参数
    Map<String, String> paramMap = HttpUtil.decodeParamMap(request.getURI().getQuery(), Charset.defaultCharset());
    String token = paramMap.get(WsSession.SESSION_KEY);
    if (StrUtil.isNotBlank(token)) {
      // 放入属性域
      attributes.put(WsSession.SESSION_KEY, token);
      log.info("握手成功:【{}】", token);
      return true;
    }
    log.info("握手失败....");
    return false;
  }

  /**
   * 握手后
   */
  @Override
  public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    log.info("结束握手, 开始交谈....");


  }
}
